package com.zhouyu.exampleThread.lockTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import lombok.extern.log4j.Log4j2;

/**
 * @Description:使用condition加锁解锁
 */
@Log4j2
public class LockConditionTest {
  private static Lock lock = new ReentrantLock();
  Condition conditionA = lock.newCondition();
  Condition conditionB = lock.newCondition();

  public void awaitA() {
    try {
      lock.lock();
      System.out.println("A开始等待：" + System.currentTimeMillis());
      //会释放锁，后面的不执行
      conditionA.await();
      System.out.println("A结束等待：" + System.currentTimeMillis());
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void awaitB() {
    try {
      lock.lock();
      System.out.println("B开始等待：" + System.currentTimeMillis());
      conditionB.await();
      System.out.println("B结束等待：" + System.currentTimeMillis());
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  /**
   * 只唤醒B线程
   */
  public void signB(){
    try {
      lock.lock();
      conditionB.signalAll();
    } finally {
      lock.unlock();
    }
  }
}
